package com.ren.mianshi.http.retrofit;

import android.annotation.SuppressLint;
import android.util.Log;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.ren.mianshi.http.convert.RGsonConverterFactory;
import com.ren.mianshi.http.gson.DoubleDefaultValueAdapter;
import com.ren.mianshi.http.gson.IntegerDefaultValueAdapter;
import com.ren.mianshi.http.gson.LongDefaultValueAdapter;

import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.concurrent.TimeUnit;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;

/**
 * RetrofitClient基类
 * Created by ren on 2017/11/21.
 */

public abstract class RRetrofitClient {


    protected Retrofit retrofit;
    protected OkHttpClient okHttpClient;
    protected Gson gson;


    /**
     * 创建OKHttp对象
     *
     * @return
     */
    protected abstract OkHttpClient createOkHttpClient();

    /**
     * 创建apiservice对象
     *
     * @param service
     * @param <T>
     * @return
     */
    public <T> T createApiService(Class<T> service) {
        return retrofit.create(service);
    }


    /**
     * 创建一个默认Retrofit对象
     *
     * @param baseUrl
     * @return
     */
    public Retrofit newDefaultRetrofit(String baseUrl) {
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(baseUrl)
                .addConverterFactory(RGsonConverterFactory.create(buildGson()))
                .client(createOkHttpClient())
                .build();
        return retrofit;
    }

    /**
     * 创建一个默认的OkHttpClient对象
     *
     * @param isHttps      是否支持Https协议
     * @param interceptors Retrofit拦截器
     * @return
     */
    public OkHttpClient newDefaultOkHttpClient(boolean isHttps, Interceptor... interceptors) {
        HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor(new RetrofitLog());
        loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        OkHttpClient.Builder builder = new OkHttpClient.Builder();

        builder.addNetworkInterceptor(loggingInterceptor)
                .readTimeout(30, TimeUnit.SECONDS)
                .connectTimeout(30, TimeUnit.SECONDS)
                .connectTimeout(30, TimeUnit.SECONDS);

        for (Interceptor interceptor : interceptors) {
            builder.addInterceptor(interceptor);
        }
        if (isHttps) {
            builder.hostnameVerifier(new TrustAllHostnameVerifier())
                    .sslSocketFactory(createSSLSocketFactory(), new TrustAllManager());
        }
        return builder.build();
    }

    /**
     * 获取OKHttpClient对象
     *
     * @return
     */
    public OkHttpClient getOkHttpClient() {
        return okHttpClient;
    }

    /**
     * 默认信任所有的证书
     * 最好加上证书认证，主流App都有自己的证书
     *
     * @return
     */
    @SuppressLint("TrulyRandom")
    public SSLSocketFactory createSSLSocketFactory() {
        SSLSocketFactory sSLSocketFactory = null;
        try {
            SSLContext sc = SSLContext.getInstance("TLS");
            sc.init(null, new TrustManager[]{new TrustAllManager()}, new SecureRandom());
            sSLSocketFactory = sc.getSocketFactory();
        } catch (Exception e) {
        }
        return sSLSocketFactory;
    }

    public class TrustAllManager implements X509TrustManager {
        @Override
        public void checkClientTrusted(X509Certificate[] chain, String authType)
                throws CertificateException {
        }

        @Override
        public void checkServerTrusted(X509Certificate[] chain, String authType)
                throws CertificateException {
        }

        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return new X509Certificate[0];
        }
    }

    public class TrustAllHostnameVerifier implements HostnameVerifier {
        @Override
        public boolean verify(String hostname, SSLSession session) {
            return true;
        }
    }

    public class RetrofitLog implements HttpLoggingInterceptor.Logger {

        @Override
        public void log(String message) {
            Log.d("Retrofit",message);
        }
    }

    public Gson buildGson() {
        if (gson == null) {
            gson = new GsonBuilder()
                    .registerTypeAdapter(Integer.class, new IntegerDefaultValueAdapter())
                    .registerTypeAdapter(int.class, new IntegerDefaultValueAdapter())
                    .registerTypeAdapter(Double.class, new DoubleDefaultValueAdapter())
                    .registerTypeAdapter(double.class, new DoubleDefaultValueAdapter())
                    .registerTypeAdapter(Long.class, new LongDefaultValueAdapter())
                    .registerTypeAdapter(long.class, new LongDefaultValueAdapter())
                    .create();
        }
        return gson;
    }
}
